#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "cJSON.h"
#include <pthread.h>
#define N 64

int main(int argc, char const *argv[])
{
    int broadfd;

    // 创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

    // 绑定套接字UDP  TCP第一次连接(ip+port)
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(7418); // 端口号
    addr.sin_addr.s_addr = INADDR_ANY;
    int addrlen = sizeof(addr);
    // UDP 绑定
    if (bind(broadfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    ssize_t len;
    char buf[N] = {0};
    char buf1[N] = "yes";
    struct sockaddr_in cliaddr;

    // 接收"coffee"搜索包
    bzero(buf, N);
    len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, &addrlen);

    // 判断是否是本公司产品：收到的数据是否"coffee"
    printf("%s\n", buf);
    if (strcmp(buf, "coffee") != 0)
    {
        printf("not my coffee\n");
        return -1;
    }
    printf("yes\n");
    // 回复yes，告诉软件，我收到了搜索协议，并且回复地址
    sendto(broadfd, buf1, strlen(buf1), 0, (struct sockaddr *)&cliaddr, addrlen);
    // 变身为TCP服务器，准备接收软件的升级文件
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);

    if (tcpfd < 0)
    {
        perror("sock err");
        return -1;
    }
    // TCP 第一次绑定
    if (bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    // 监听套接字
    if (listen(tcpfd, 5) < 0)
    {
        perror("listen err");
        return -1;
    }

    // 接收客户端的连接
    printf("wait client connect\n");
    int clifd, Aclifd;
    char recvbuf[10240] = {};
    char recvbuf2[10240] = {};
    char sendbuf[N] = "fa";
    char sendbuf2[N] = "living";
    // 接收对端的地址
    clifd = accept(tcpfd, NULL, NULL);
    if (clifd < 0)
    {
        perror("accept err");
        return -1;
    }

    printf("new cononect coming\n");
    int recv_n = 0;
    int recv_n2 = 0;
    while (1)
    {
        //循环读取第一次TCP连接
        recv_n = recv(clifd, recvbuf, 10240, 0);
        printf("%s\n", recvbuf);
        if (recv_n < 0)
            return -1;
        cJSON *root = cJSON_Parse(recvbuf);
        if (root == NULL)
        {
            printf("JSON parse error\n");
        }
        //读item valueint
        cJSON *item = cJSON_GetObjectItem(root, "type");
        if (item != NULL)
        {
            int type = item->valueint;
            //值为1 时下发点表
            if (type == 1)
            {
                send(clifd, sendbuf, strlen(sendbuf), 0);
                printf("copy....\n");
                //建立 第二次TCP连接
                int Atcpfd = socket(AF_INET, SOCK_STREAM, 0);
                struct sockaddr_in Aaddr;
                Aaddr.sin_family = AF_INET;
                Aaddr.sin_port = htons(7417); // 端口号
                Aaddr.sin_addr.s_addr = INADDR_ANY;
                int Aaddrlen = sizeof(Aaddr);
                if (bind(Atcpfd, (struct sockaddr *)&Aaddr, Aaddrlen) < 0)
                {
                    perror("bind err");
                    pthread_exit(NULL);
                }

                // 启动监听
                if (listen(Atcpfd, 5) < 0)
                {
                    perror("listen err");
                    pthread_exit(NULL);
                }

                // 接收连接
                Aclifd = accept(Atcpfd, (struct sockaddr *)&cliaddr, &addrlen);
                int fd = open("/mnt/config/table.json", O_WRONLY | O_CREAT | O_TRUNC, 0777);
                if (fd < 0)
                {
                    perror("open err");
                }
                while (1)
                {
                    //循环读取发过来的点表
                    recv_n2 = recv(Aclifd, recvbuf2, 10240, 0);
                    if (recv_n2 <= 0)
                    {
                        break;
                    }
                    // 拷贝配置文件
                    write(fd, recvbuf2, recv_n2);
                    close(fd);
                    break;
                }
                //关闭第二次TCP连接的套接字
                close(Aclifd);
                printf("copy success!\n");
            }
            //心跳包回发
            if (type == 3)
            {
                if (send(clifd, sendbuf2, strlen(sendbuf2), 0) < 0)
                {
                    perror("send err\n");
                }
            }
        }
    }

    return 0;
}
